package com.ruoyi.phoneController;

import java.util.List;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.domain.CarMessage;
import com.ruoyi.domain.CarGasStation;
import com.ruoyi.domain.CarCoupon;
import com.ruoyi.domain.CarGroupPurchase;
import com.ruoyi.domain.CarConsumptionRecord;
import com.ruoyi.service.ICarMessageService;
import com.ruoyi.service.ICarGasStationService;
import com.ruoyi.service.ICarCouponService;
import com.ruoyi.service.ICarUserCouponService;
import com.ruoyi.service.ICarGroupPurchaseService;
import com.ruoyi.service.ICarConsumptionRecordService;
import com.ruoyi.domain.CarUserCoupon;

/**
 * 移动端API控制器
 * 
 * @author ruoyi
 * @date 2025-01-27
 */
@RestController
@RequestMapping("/mobile")
@CrossOrigin(origins = "*", maxAge = 3600)
public class MobileController extends BaseController
{
    @Autowired
    private ICarMessageService carMessageService;

    @Autowired
    private ICarGasStationService carGasStationService;

    @Autowired
    private ICarCouponService carCouponService;

    @Autowired
    private ICarUserCouponService carUserCouponService;

    @Autowired
    private ICarGroupPurchaseService carGroupPurchaseService;

    @Autowired
    private ICarConsumptionRecordService carConsumptionRecordService;

    // ==================== 消息中心相关接口 ====================

    /**
     * 获取用户消息列表
     */
    @GetMapping("/messages")
    public AjaxResult getMessages(@RequestParam Integer userId)
    {
        try {
            List<CarMessage> messages = carMessageService.selectCarMessageByUserId(userId);
            return AjaxResult.success(messages);
        } catch (Exception e) {
            return AjaxResult.error("获取消息列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取所有消息（用于测试显示所有数据）
     */
    @GetMapping("/messages/all")
    public AjaxResult getAllMessages()
    {
        try {
            List<CarMessage> messages = carMessageService.selectCarMessageList(new CarMessage());
            return AjaxResult.success(messages);
        } catch (Exception e) {
            return AjaxResult.error("获取所有消息失败：" + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/messages/{id}/read")
    public AjaxResult markMessageAsRead(@PathVariable Integer id)
    {
        try {
            int result = carMessageService.markMessageAsRead(id);
            if (result > 0) {
                return AjaxResult.success("标记成功");
            } else {
                return AjaxResult.error("标记失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("标记失败：" + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     */
    @GetMapping("/messages/unread/count")
    public AjaxResult getUnreadMessageCount(@RequestParam Integer userId)
    {
        try {
            int count = carMessageService.getUnreadMessageCount(userId);
            Map<String, Object> data = new HashMap<>();
            data.put("count", count);
            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error("获取未读消息数量失败：" + e.getMessage());
        }
    }

    // ==================== 加油站相关接口 ====================

    /**
     * 获取加油站列表
     */
    @GetMapping("/gas-stations")
    public AjaxResult getGasStations()
    {
        try {
            List<CarGasStation> gasStations = carGasStationService.selectCarGasStationList(new CarGasStation());
            return AjaxResult.success(gasStations);
        } catch (Exception e) {
            return AjaxResult.error("获取加油站列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据经纬度查询附近加油站
     */
    @GetMapping("/gas-stations/nearby")
    public AjaxResult getNearbyGasStations(
            @RequestParam String latitude,
            @RequestParam String longitude,
            @RequestParam(defaultValue = "5000") Integer radius)
    {
        try {
            List<CarGasStation> gasStations = carGasStationService.selectNearbyGasStations(latitude, longitude, radius);
            return AjaxResult.success(gasStations);
        } catch (Exception e) {
            return AjaxResult.error("获取附近加油站失败：" + e.getMessage());
        }
    }

    /**
     * 根据关键词搜索加油站
     */
    @GetMapping("/gas-stations/search")
    public AjaxResult searchGasStations(@RequestParam String keyword)
    {
        try {
            List<CarGasStation> gasStations = carGasStationService.searchGasStationsByKeyword(keyword);
            return AjaxResult.success(gasStations);
        } catch (Exception e) {
            return AjaxResult.error("搜索加油站失败：" + e.getMessage());
        }
    }

    /**
     * 获取加油站详情
     */
    @GetMapping("/gas-stations/{id}")
    public AjaxResult getGasStationDetail(@PathVariable Integer id)
    {
        try {
            CarGasStation gasStation = carGasStationService.selectCarGasStationById(id);
            if (gasStation != null) {
                return AjaxResult.success(gasStation);
            } else {
                return AjaxResult.error("加油站不存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取加油站详情失败：" + e.getMessage());
        }
    }

    // ==================== 优惠券相关接口 ====================

    /**
     * 获取所有优惠券列表
     */
    @GetMapping("/coupons")
    public AjaxResult getAllCoupons()
    {
        try {
            List<CarCoupon> coupons = carCouponService.selectCarCouponList(new CarCoupon());
            return AjaxResult.success(coupons);
        } catch (Exception e) {
            return AjaxResult.error("获取优惠券列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取可领取的优惠券列表
     */
    @GetMapping("/coupons/available")
    public AjaxResult getAvailableCoupons()
    {
        try {
            List<CarCoupon> coupons = carCouponService.selectAvailableCoupons();
            return AjaxResult.success(coupons);
        } catch (Exception e) {
            return AjaxResult.error("获取优惠券列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据商家ID获取优惠券列表
     */
    @GetMapping("/coupons/merchant/{merchantId}")
    public AjaxResult getCouponsByMerchant(@PathVariable Integer merchantId)
    {
        try {
            List<CarCoupon> coupons = carCouponService.selectCarCouponByMerchantId(merchantId);
            return AjaxResult.success(coupons);
        } catch (Exception e) {
            return AjaxResult.error("获取商家优惠券失败：" + e.getMessage());
        }
    }

    /**
     * 领取优惠券
     */
    @PostMapping("/coupons/{couponId}/receive")
    public AjaxResult receiveCoupon(@PathVariable Integer couponId, @RequestParam Integer userId)
    {
        try {
            int result = carCouponService.receiveCoupon(couponId, userId);
            if (result > 0) {
                return AjaxResult.success("领取成功");
            } else {
                return AjaxResult.error("领取失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("领取失败：" + e.getMessage());
        }
    }

    /**
     * 使用优惠券
     */
    @PostMapping("/coupons/{couponId}/use")
    public AjaxResult useCoupon(@PathVariable Integer couponId, @RequestParam Integer userId)
    {
        try {
            int result = carUserCouponService.useCoupon(couponId.longValue(), userId.longValue());
            if (result > 0) {
                return AjaxResult.success("使用成功");
            } else {
                return AjaxResult.error("使用失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("使用失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户优惠券列表
     */
    @GetMapping("/user-coupons")
    public AjaxResult getUserCoupons(@RequestParam Integer userId)
    {
        try {
            List<CarUserCoupon> userCoupons = carUserCouponService.selectCarUserCouponByUserId(userId.longValue());
            return AjaxResult.success(userCoupons);
        } catch (Exception e) {
            return AjaxResult.error("获取用户优惠券失败：" + e.getMessage());
        }
    }

    // ==================== 团购相关接口 ====================

    /**
     * 获取有效的团购活动列表
     */
    @GetMapping("/group-purchases/active")
    public AjaxResult getActiveGroupPurchases()
    {
        try {
            List<CarGroupPurchase> groupPurchases = carGroupPurchaseService.selectActiveGroupPurchases();
            return AjaxResult.success(groupPurchases);
        } catch (Exception e) {
            return AjaxResult.error("获取团购活动列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取团购详情
     */
    @GetMapping("/group-purchases/{id}")
    public AjaxResult getGroupPurchaseDetail(@PathVariable Integer id)
    {
        try {
            CarGroupPurchase groupPurchase = carGroupPurchaseService.selectCarGroupPurchaseById(id);
            if (groupPurchase != null) {
                return AjaxResult.success(groupPurchase);
            } else {
                return AjaxResult.error("团购活动不存在");
            }
        } catch (Exception e) {
            return AjaxResult.error("获取团购详情失败：" + e.getMessage());
        }
    }

    /**
     * 参与团购
     */
    @PostMapping("/group-purchases/{id}/join")
    public AjaxResult joinGroupPurchase(@PathVariable Integer id, @RequestParam Integer userId)
    {
        try {
            // 检查团购是否可参与
            if (!carGroupPurchaseService.isGroupPurchaseAvailable(id)) {
                return AjaxResult.error("团购活动不可参与");
            }

            int result = carGroupPurchaseService.joinGroupPurchase(id, userId);
            if (result > 0) {
                return AjaxResult.success("参与成功");
            } else {
                return AjaxResult.error("参与失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("参与失败：" + e.getMessage());
        }
    }

    /**
     * 获取团购参与人数
     */
    @GetMapping("/group-purchases/{id}/participants/count")
    public AjaxResult getGroupPurchaseParticipantCount(@PathVariable Integer id)
    {
        try {
            int count = carGroupPurchaseService.getGroupPurchaseParticipantCount(id);
            Map<String, Object> data = new HashMap<>();
            data.put("count", count);
            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error("获取参与人数失败：" + e.getMessage());
        }
    }

    // ==================== 消费记录相关接口 ====================

    /**
     * 获取所有消费记录列表（用于测试，显示所有用户数据）
     */
    @GetMapping("/consumption-records/all")
    public AjaxResult getAllConsumptionRecords()
    {
        try {
            List<CarConsumptionRecord> records = carConsumptionRecordService.selectCarConsumptionRecordList(new CarConsumptionRecord());
            return AjaxResult.success(records);
        } catch (Exception e) {
            return AjaxResult.error("获取所有消费记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户消费记录列表
     */
    @GetMapping("/consumption-records")
    public AjaxResult getConsumptionRecords(@RequestParam Integer userId)
    {
        try {
            List<CarConsumptionRecord> records = carConsumptionRecordService.selectCarConsumptionRecordByUserId(userId);
            return AjaxResult.success(records);
        } catch (Exception e) {
            return AjaxResult.error("获取消费记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据消费类型获取消费记录
     */
    @GetMapping("/consumption-records/type")
    public AjaxResult getConsumptionRecordsByType(
            @RequestParam Integer userId,
            @RequestParam Integer consumptionType)
    {
        try {
            List<CarConsumptionRecord> records = carConsumptionRecordService.selectCarConsumptionRecordByType(userId, consumptionType);
            return AjaxResult.success(records);
        } catch (Exception e) {
            return AjaxResult.error("获取消费记录失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户消费统计
     */
    @GetMapping("/consumption-records/statistics")
    public AjaxResult getConsumptionStatistics(@RequestParam Integer userId)
    {
        try {
            Object statistics = carConsumptionRecordService.getUserConsumptionStatistics(userId);
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            return AjaxResult.error("获取消费统计失败：" + e.getMessage());
        }
    }

    // ==================== 健康检查接口 ====================

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public AjaxResult health()
    {
        Map<String, Object> data = new HashMap<>();
        data.put("status", "UP");
        data.put("timestamp", System.currentTimeMillis());
        return AjaxResult.success(data);
    }
}
